const router = require( 'koa-router' )();
const userTable = require( '../models/user' );
const userGuide = require( '../models/user_guide' );
const planTable = require( '../models/plan' );
const settingTable = require( '../models/setting' );
const dataAdminRegion = require( '../models/admin_region' );
const dataCategory = require('../models/data_category');
const organization = require('../models/organization');
const config = require('../config');
const appSetting = require('../setting');

const headers = { 'Content-Type': 'application/json', 'Encoding': 'utf8' };

const nameMap = {
    free: '免费版',
    standard: '标准版',
    advanced: '高级版',
    enterprise: '企业版'
}

router.get( '*', async function ( ctx ) {

    if ( !ctx.request.cookies || !ctx.request.cookies.userId ) {
        return ctx.redirect( '/sign' );
    }

    let userId = ctx.request.cookies.userId;

    let rows = await userTable.getUser( userId );
    let userData = rows[ 0 ];

    let newUserGuide = false;
    if(appSetting.getSetting('platform.userguide') === 'true'){
        let user = await userGuide.getUserById(userId);
        newUserGuide = (user && user.rowCount) ? false : true;
    }

    let data = {
        id: userData.id,
        name: userData.name,
        email: userData.email,
        role: userData.role,
        userGuide: newUserGuide
    }

    let planData = await planTable.getAll();
    planData.forEach( item => {
        item.alias = nameMap[ item.name ];
    } )

    let uploadLimit = appSetting.getSetting('data.upload.limit');
    let functionSwitch = {
        download: appSetting.getSetting('platform.download')
    }

    let cities = await dataAdminRegion.getAll();
    if (!cities) {
        cities = [];
    }
    let categories = await dataCategory.getAll();
    if (!categories) {
        categories = [];
    }
    let componentConfs = await settingTable.getComponentConf();
    
    if (!componentConfs) {
        componentConfs = '{}';
    }

    let org = await organization.getorg(userId);
    let userOrg = {};

    if (org) {
        userOrg.orgUid = org.org_uid;
        userOrg.role = org.role
    }

    return ctx.render( 'platform', {
        user: new Buffer( JSON.stringify( data ) ).toString( 'base64' ),
        plan: new Buffer( JSON.stringify( planData ) ).toString( 'base64' ),
        upload_limit: new Buffer( JSON.stringify( {upload_limit: uploadLimit} ) ).toString( 'base64' ),
        data_category: new Buffer( JSON.stringify( categories ) ).toString( 'base64' ),
        admin_region: new Buffer( JSON.stringify( cities ) ).toString( 'base64' ),
        component_conf: new Buffer(componentConfs).toString( 'base64' ),
        org: new Buffer(JSON.stringify(userOrg)).toString('base64'),
        show_wgs84_download_option: config.showWgs84DownloadOption,
        page: JSON.stringify(config.page),
        function_switch: JSON.stringify(functionSwitch),
        backend_env: config['ENV']
    } );
} )

module.exports = router;
